﻿using System;
using System.Diagnostics;

namespace Job.Core.Common
{
    /// <summary>
    /// 代码运行性能测试器。
    /// </summary>
    public static class CodeTimer
    {
        /// <summary>
        /// 执行一段代码，返回执行所花费的时间。
        /// </summary>
        /// <param name="name">执行名称。</param>
        /// <param name="iteration">执行次数。</param>
        /// <param name="action">需执行的委托。</param>
        /// <returns>返回执行名称 + 执行所花费的时间。</returns>
        public static string Run(string name, int iteration, Action action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < iteration; i++) action();
            watch.Stop();

            return string.Format("{0} : {1}ms", name, watch.ElapsedMilliseconds.ToString("N0"));            
        }
    }
}